﻿using System.Web;
using System.Web.Mvc;
using WSS.Models.User;
using WSS.Pub;

namespace WSS.Web.Controllers
{
    public class MyController : Controller
    {
        protected WSS.BLL.Account.IAccount AccountCache { get; private set; }

        protected override void OnAuthorization(AuthorizationContext filterContext)
        {

            if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
            {
                return;
            }

            string userdata = ((System.Web.Security.FormsIdentity)(filterContext.HttpContext.User.Identity)).Ticket.UserData;

            if (string.IsNullOrEmpty(userdata))
            {
                return;
            }

            string[] arr_userdata = userdata.Split(',');

            if (arr_userdata.Length != 4)
            {
                return;
            }


            string guid = arr_userdata[0];
            string userid = arr_userdata[1];
            string userno = arr_userdata[2];
            string hospitalid = arr_userdata[3];

            var online = new WSS.BLL.Account.OnlineHelper();

            //登录数据丢失
            if (online.GetUserInfoByGuid(guid) == null)
            {
                //return;
                //本段代码在开发阶段防重复登录用，正式发布需要注释
                USER_USER user = DB.Load<USER_USER, PK_USER_USER>(new PK_USER_USER
                {
                    HOSP_ID = hospitalid,
                    USER_ID = userid,
                    USER_NO = userno
                });
                online.CacheUserData(user, guid, filterContext.HttpContext.Request.RawUrl);
            }
            else
            {
                var request = filterContext.HttpContext.Request;

                if (request.Url != null) online.UpdateUserLastAction(guid, request.Url.AbsolutePath);

            }

            WSS.BLL.Account.IAccount account = new WSS.BLL.Account.Account(guid);
            if (account.IsLogon)
            {
                ViewBag.UserId = account.UserId;
                ViewBag.UserName = account.UserName;
                ViewBag.UserNo = account.CurrentUserInfo.UserInfo.USER_NO;
                ViewBag.HospitalId = account.CurrentUserInfo.UserInfo.HOSP_ID;
                AccountCache = account;
            }

            base.OnAuthorization(filterContext);
        }
    }
}